<template>
  <div class="voice-recorder">
    <div class="recorder-container" style="display: none">
      <!-- 录音状态显示 -->
      <div class="recorder-status" style="display: none">
        <div class="status-indicator" :class="recordingStatus">
          <div class="pulse-ring" v-if="isRecording"></div>
          <el-icon class="status-icon">
            <Microphone v-if="!isRecording" />
            <VideoPause v-else />
          </el-icon>
        </div>
        <span class="status-text">{{ statusText }}</span>
      </div>

      <!-- 录音计时 -->
      <div
        class="recording-timer"
        v-if="isRecording || isPaused"
        style="display: none"
      >
        <div class="timer-display">
          <span class="timer-text">{{ formatTime(recordingTime) }}</span>
        </div>
        <div class="wave-animation" v-if="isRecording">
          <div class="wave-bar" v-for="i in 5" :key="i"></div>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="control-buttons">
        <!-- 开始/停止录音 -->
        <!-- <el-button 
          type="primary" 
          :icon="isRecording ? VideoPause : Microphone"
          @click="toggleRecording"
          :disabled="!isSupported"
          class="record-btn"
        >
          {{ isRecording ? '停止录音' : '开始录音' }}
        </el-button> -->
        <el-button @click="clearTranscript"> 清空 </el-button>
        <el-button v-if="isRecording" @click="togglePause">
          {{ isPaused ? '继续' : '暂停' }}
        </el-button>
        <el-button
          type="primary"
          @click="toggleRecording"
          :disabled="!isSupported"
          v-if="isSupported"
        >
          开始3
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="toggleRecording"
          :disabled="!isSupported"
        >
          完成2
        </el-button>
        <!-- 暂停/继续 -->

        <!-- 清空 -->
        <!-- <el-button 
          v-if="transcriptText"
          icon="Delete"
          @click="clearTranscript"
          class="clear-btn"
        >
          清空
        </el-button> -->
      </div>

      <!-- 转换的文字内容 -->
      <div class="transcript-container" v-if="transcriptText || interimText">
        <div class="transcript-label">识别结果：</div>
        <div class="transcript-content">
          <span class="final-text">{{ transcriptText }}</span>
          <span class="interim-text">{{ interimText }}</span>
          <span class="cursor" v-if="isRecording">|</span>
        </div>
      </div>

      <!-- 错误信息 -->
      <div class="error-message" v-if="errorMessage">
        <el-alert :title="errorMessage" type="error" show-icon />
      </div>
    </div>
    <div class="recorder-box">
      <div>
        <div class="timer-display">
          <span class="timer-text">{{ formatTime(recordingTime) }}</span>
        </div>
        <div class="wave-animation" v-if="isRecording">
          <div class="wave-bar" v-for="i in 5" :key="i"></div>
        </div>
        <div
          v-if="!transcriptText"
          style="
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            color: rgba(0, 0, 0, 0.2);
            height: 250px;
          "
        >
          请说话，我会将语音转文字...
        </div>
        <div
          v-else
          style="
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            color: black;
            height: 250px;
            overflow: auto;
          "
        >
          <span class="final-text">{{ transcriptText }}</span>
        </div>
        <div class="control-buttons">
          <!-- <el-button @click="clearTranscript" v-if="formatTime(recordingTime)"> 清空 </el-button> -->
          <el-button v-if="isRecording" @click="togglePause">
            {{ isPaused ? '继续' : '暂停' }}
          </el-button>
          <el-button
            type="primary"
            @click="toggleRecording"
            :disabled="!isSupported"
            v-if="isRecording"
          >
            {{ '完成' }}
          </el-button>
          <el-button
            v-if="!isRecording"
            type="primary"
            @click="toggleRecording"
            :disabled="!isSupported"
          >
            {{ '开始' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import {
  Microphone,
  VideoPause,
  VideoPlay,
  Delete,
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 声明全局类型
declare global {
  interface Window {
    webkitSpeechRecognition: any;
    SpeechRecognition: any;
  }
}

// Props
interface Props {
  language?: string;
  continuous?: boolean;
  interimResults?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  language: 'zh-CN',
  continuous: true,
  interimResults: true,
});

// Emits
const emit = defineEmits<{
  result: [text: string];
  'interim-result': [text: string];
  'recording-start': [];
  'recording-stop': [text: string];
  'recording-pause': [];
  'recording-resume': [];
  error: [error: string];
}>();

// 响应式数据
const isSupported = ref(false);
const isRecording = ref(false);
const isPaused = ref(false);
const recordingTime = ref(0); // 录音时间，以毫秒为单位
const transcriptText = ref('');
const interimText = ref('');
const errorMessage = ref('');

// 语音识别相关
const recognition = ref<any>(null);
const recordingTimer = ref<ReturnType<typeof setInterval> | null>(null);

// 计算属性
const recordingStatus = computed(() => {
  if (isRecording.value && !isPaused.value) return 'recording';
  if (isPaused.value) return 'paused';
  return 'stopped';
});

const statusText = computed(() => {
  if (isRecording.value && !isPaused.value) return '正在录音...';
  if (isPaused.value) return '已暂停';
  if (transcriptText.value) return '录音完成';
  return '准备录音';
});

// 初始化语音识别
const initSpeechRecognition = () => {
  if (
    !('webkitSpeechRecognition' in window) &&
    !('SpeechRecognition' in window)
  ) {
    isSupported.value = false;
    errorMessage.value =
      '您的浏览器不支持语音识别功能，请使用Chrome、Edge或Safari浏览器';
    return;
  }

  isSupported.value = true;
  const SpeechRecognition =
    window.SpeechRecognition || window.webkitSpeechRecognition;
  recognition.value = new SpeechRecognition();

  // 配置语音识别
  recognition.value.continuous = props.continuous;
  recognition.value.interimResults = props.interimResults;
  recognition.value.lang = props.language;
  recognition.value.maxAlternatives = 1;

  // 监听事件
  recognition.value.onstart = () => {
    //console.log('语音识别开始');
    emit('recording-start');
  };

  recognition.value.onresult = (event: any) => {
    let finalTranscript = '';
    let interimTranscript = '';

    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcript = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        finalTranscript += transcript;
      } else {
        interimTranscript += transcript;
      }
    }

    if (finalTranscript) {
      transcriptText.value += finalTranscript;
      emit('result', transcriptText.value);
    }

    interimText.value = interimTranscript;
    if (interimTranscript) {
      emit('interim-result', interimTranscript);
    }
  };

  recognition.value.onerror = (event: any) => {
    //console.error('语音识别错误:', event.error);
    let errorMsg = '语音识别错误';

    switch (event.error) {
      case 'no-speech':
        errorMsg = '未检测到语音，请重试';
        break;
      case 'audio-capture':
        errorMsg = '无法访问麦克风';
        break;
      case 'not-allowed':
        errorMsg = '麦克风访问被拒绝';
        break;
      case 'network':
        errorMsg = '网络错误，请检查网络连接';
        break;
      default:
        errorMsg = `语音识别错误: ${event.error}`;
    }

    errorMessage.value = errorMsg;
    //ElMessage.error(errorMsg);
    stopRecording();
    emit('error', errorMsg);
  };

  recognition.value.onend = () => {
    //console.log('语音识别结束');
    if (isRecording.value && !isPaused.value) {
      // 如果应该继续录音但识别结束了，重新启动
      try {
        recognition.value.start();
      } catch (error) {
        //console.error('重启语音识别失败:', error);
      }
    }
  };
};

// 开始/停止录音
const toggleRecording = () => {
  if (isRecording.value) {
    stopRecording();
  } else {
    // 开始录音
    startRecording();
  }
};

// 开始录音
const startRecording = () => {
  if (!isSupported.value) {
    ElMessage.warning('您的浏览器不支持语音识别功能');
    return;
  }

  try {
    errorMessage.value = '';
    isRecording.value = true;
    isPaused.value = false;
    recordingTime.value = 0;

    recognition.value.start();
    startTimer();

    ElMessage.success('开始录音');
    emit('recording-start');
  } catch (error) {
    //console.error('开始录音失败:', error);
    //ElMessage.error('开始录音失败');
    isRecording.value = false;
  }
};

// 停止录音
const stopRecording = () => {
  if (recognition.value) {
    recognition.value.stop();
  }

  isRecording.value = false;
  isPaused.value = false;
  stopTimer();
  interimText.value = '';
  clearTranscript();
  ElMessage.info('录音已停止');
  //console.log(transcriptText.value);
  emit('recording-stop', transcriptText.value);
};

// 暂停/继续录音
const togglePause = () => {
  if (isPaused.value) {
    resumeRecording();
  } else {
    pauseRecording();
  }
};

// 暂停录音
const pauseRecording = () => {
  if (recognition.value) {
    recognition.value.stop();
  }
  isPaused.value = true;
  stopTimer();
  interimText.value = '';
  ElMessage.info('录音已暂停');
  emit('recording-pause');
};

// 继续录音
const resumeRecording = () => {
  if (!isSupported.value) return;

  try {
    isPaused.value = false;
    recognition.value.start();
    startTimer();

    ElMessage.success('继续录音');
    emit('recording-resume');
  } catch (error) {
    //console.error('继续录音失败:', error);
    //ElMessage.error('继续录音失败');
  }
};

// 清空转录文本
const clearTranscript = () => {
  transcriptText.value = '';
  interimText.value = '';
  errorMessage.value = '';
  recordingTime.value = 0;
};
const onClose = () => {
  if (recognition.value) {
    recognition.value.stop();
  }
  stopTimer();
  clearTranscript();
  isRecording.value = false;
};

// 开始计时
const startTimer = () => {
  recordingTimer.value = setInterval(() => {
    recordingTime.value += 100; // 每100毫秒增加100
  }, 100); // 每100毫秒更新一次
};

// 停止计时
const stopTimer = () => {
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value);
    recordingTimer.value = null;
  }
};

// 格式化时间 - 支持分钟:秒:毫秒格式
const formatTime = (milliseconds: number): string => {
  const totalSeconds = Math.floor(milliseconds / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const mins = Math.floor((totalSeconds % 3600) / 60);
  const secs = totalSeconds % 60;
  const ms = Math.floor((milliseconds % 1000) / 10); // 取两位毫秒

  if (hours > 0) {
    // 如果有小时，显示 HH:MM:SS.MS 格式
    return `${hours.toString().padStart(2, '0')}:${mins
      .toString()
      .padStart(2, '0')}:${secs.toString().padStart(2, '0')}:${ms
      .toString()
      .padStart(2, '0')}`;
  } else {
    // 如果没有小时，显示 MM:SS.MS 格式
    return `${mins.toString().padStart(2, '0')}:${secs
      .toString()
      .padStart(2, '0')}:${ms.toString().padStart(2, '0')}`;
  }
};

// 生命周期
onMounted(() => {
  initSpeechRecognition();
});

onUnmounted(() => {
  if (isRecording.value) {
    stopRecording();
  }
  stopTimer();
});

// 暴露方法
defineExpose({
  startRecording,
  stopRecording,
  pauseRecording,
  resumeRecording,
  clearTranscript,
  onClose,
  isRecording: () => isRecording.value,
  isPaused: () => isPaused.value,
  getTranscript: () => transcriptText.value,
});
</script>

<style lang="scss" scoped>
.recorder-box {
  width: 100%;
  height: 300px;
}
.voice-recorder {
  width: 100%;
}

.recorder-container {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.recorder-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;

  .status-indicator {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12px;
    transition: all 0.3s ease;

    &.stopped {
      background: #f3f4f6;
      border: 2px solid #d1d5db;
    }

    &.recording {
      background: #fee2e2;
      border: 2px solid #ef4444;
      animation: pulse 2s infinite;
    }

    &.paused {
      background: #fef3c7;
      border: 2px solid #f59e0b;
    }

    .pulse-ring {
      position: absolute;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 2px solid #ef4444;
      animation: pulse-ring 1.5s infinite;
    }

    .status-icon {
      font-size: 32px;
      color: #374151;
      z-index: 1;
    }
  }

  .status-text {
    font-size: 16px;
    font-weight: 500;
    color: #374151;
  }
}

.recording-timer {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;

  .timer-display {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 12px;

    .timer-label {
      font-size: 12px;
      color: #6b7280;
      margin-bottom: 4px;
      font-weight: 500;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .timer-text {
      font-size: 32px;
      font-weight: bold;
      color: #1f2937;
      font-family: 'Courier New', monospace;
      background: linear-gradient(135deg, #3b82f6, #1d4ed8);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      text-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
    }
  }

  .wave-animation {
    display: flex;
    align-items: center;
    gap: 4px;
    height: 30px;

    .wave-bar {
      width: 4px;
      background: #3b82f6;
      border-radius: 2px;
      animation: wave 1.2s infinite ease-in-out;

      &:nth-child(1) {
        animation-delay: -1.2s;
      }
      &:nth-child(2) {
        animation-delay: -1.1s;
      }
      &:nth-child(3) {
        animation-delay: -1s;
      }
      &:nth-child(4) {
        animation-delay: -0.9s;
      }
      &:nth-child(5) {
        animation-delay: -0.8s;
      }
    }
  }
}

.control-buttons {
  display: flex;
  justify-content: center;
  margin: 10px auto;
  .el-button {
    padding: 12px 40px;
    font-size: 14px;
    border-radius: 8px;
  }

  .record-btn {
    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #1d4ed8, #1e40af);
    }
  }

  .pause-btn {
    background: #f59e0b;
    border-color: #f59e0b;
    color: white;

    &:hover {
      background: #d97706;
      border-color: #d97706;
    }
  }

  .clear-btn {
    background: #ef4444;
    border-color: #ef4444;
    color: white;

    &:hover {
      background: #dc2626;
      border-color: #dc2626;
    }
  }
}

.transcript-container {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;

  .transcript-label {
    font-size: 14px;
    font-weight: 600;
    color: #374151;
    margin-bottom: 8px;
  }

  .transcript-content {
    min-height: 60px;
    max-height: 200px;
    overflow-y: auto;
    line-height: 1.6;
    font-size: 16px;

    .final-text {
      color: #1f2937;
    }

    .interim-text {
      color: #6b7280;
      font-style: italic;
    }

    .cursor {
      color: #3b82f6;
      animation: blink 1s infinite;
    }
  }
}

.error-message {
  margin-top: 16px;
}

// 动画
@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes pulse-ring {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(1.3);
    opacity: 0;
  }
}

@keyframes wave {
  0%,
  40%,
  100% {
    height: 5px;
  }
  20% {
    height: 25px;
  }
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0;
  }
}
</style>
